# encoding: utf-8

import json
import urllib
import re

def main(env):
	text = env["context"]["selection"]
	d = {"word":text.strip()}
	if text.strip() == "":
		return [("messageBox",env["static"]["cwSynonyms_emptyWordMessage"] % d)]
	baseUrl = "http://www.crisco.unicaen.fr/des/synonymes/"
	word = repr(text.encode('utf8')).strip().replace(r"\x","%")[1:-1]
	page = urllib.urlopen(baseUrl+word).read().decode("utf8")
	try:
		page = re.search(r"""(?s)<div id="synonymes">.+?<!--Liste des antonymes-->""",page).group(0)
	except AttributeError:
		return [("messageBox",env["static"]["cwSynonyms_noEntryMessage"] % d)]
	potentialSpace = " " if text.endswith(" ") else ""
	synonyms = [match.group(1)+potentialSpace for match in re.finditer(r"""<a href="/des/synonymes/.+?">(.+?)</a>""",page)]
	d["count"] = len(synonyms)
	return [("listBox",{
			"items":synonyms,
			"label": (env["static"]["cwSynonyms_labelOne"] % d if d["count"]==1 else env["static"]["cwSynonyms_labelSeveral"] % d)
		})]

